package cn.wecloud.im.multiplayervideodemo.fragment

import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import cn.wecloud.im.core.im.messages.Command
import cn.wecloud.im.multiplayervideodemo.R
import cn.wecloud.im.multiplayervideodemo.ext.loadAvatar
import cn.wecloud.im.multiplayervideodemo.ext.loadUrl
import cn.wecloud.im.multiplayervideodemo.utils.StringUtils
import kotlinx.android.synthetic.main.fragment_video_call.*

/**
 * 呼叫页面
 */
class VideoCallFragment : androidx.fragment.app.Fragment() {

    companion object {
        private const val CLIENT_ID = "client_id"
        private const val RTC_TYPE = "rtc_type"

        @JvmStatic
        fun newInstance(clientId: String, rtcType: Int) =
            VideoCallFragment().apply {
                arguments = Bundle().apply {
                    putString(CLIENT_ID, clientId)
                    putInt(RTC_TYPE, rtcType)
                }
            }
    }

    private var clientId: String? = null
    private var rtcType: Int? = null
    var hangupCallback: ((Long) -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            clientId = it.getString(CLIENT_ID)
            rtcType = it.getInt(RTC_TYPE, 0)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_video_call, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        tvUserName.text =  clientId
        ivAvatar.loadAvatar("")
        ivBackGround.loadUrl("", R.mipmap.ic_avatar, true)
        groupMask.isVisible = rtcType == Command.WeRtcType.RTC_TYPE_VOICE.code
        ivHangUp.setOnClickListener {
            //挂断
            val duration = getTimeToSecond()
            hangupCallback?.invoke(duration)
        }
        startCallTime()
    }

    fun getTimeToSecond(): Long {
        return StringUtils.getChronometerSeconds(tvTime) * 1000L
    }

    //开始计时通话时间
    private fun startCallTime() {
        tvTime.base = SystemClock.elapsedRealtime()
        tvTime.start()
    }

    override fun onDestroy() {
        if (tvTime != null) {
            tvTime.stop()
        }
        super.onDestroy()
    }
}